package com.murong.ai.chat.domain.chatbot.rasa;

import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.murong.ai.chat.domain.chatbot.ChatBotService;
import com.murong.ai.chat.domain.chatbot.rasa.module.RasaAiRequest;
import com.murong.ai.chat.infrastructure.httprequest.HttpClientService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.net.http.HttpResponse;

@Service("rasaCall")
@ConditionalOnProperty(name = "chat.bot.call.service", havingValue = "rasa", matchIfMissing = false)
public class RasaService extends HttpClientService<RasaAiRequest,String> implements ChatBotService {

    private RasaAiRequest openAiRequest;
    private Environment environment;

    public RasaService(Environment environment){
        this.environment=environment;
    }

    @Override
    public String call(String content) {
        if(openAiRequest==null){
            openAiRequest = new RasaAiRequest();
        }
        openAiRequest.setMessage(content);
        return request(openAiRequest);
    }

    @Override
    public String buildResponseBody(HttpResponse<String> response) {
        JsonArray jsonArray = JsonParser.parseString(response.body()).getAsJsonArray();
        return jsonArray.get(0).getAsJsonObject().get("text").getAsString();
    }

    @Override
    public String getUri() {
        return environment.getProperty("chat.bot.rasa.http.uri");
    }

}
